package com.lkk.cg.util;

import com.lkk.cg.domain.Privilege;
import com.lkk.cg.service.PrivilegeService;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lkk on 2014/12/6.
 */
public class InitListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        //ApplicationContext ac = (ApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        PrivilegeService privilegeService = (PrivilegeService) ac.getBean("privilegeService");

        List<Privilege> allPrivileges = privilegeService.getAll();
        List<Privilege> privilegesNeedLogin = new ArrayList<Privilege>();
        List<Privilege> privilegesNeedAuth = new ArrayList<Privilege>();

        for (Privilege p : allPrivileges) {
            if (p.getType() == 1)
                privilegesNeedAuth.add(p);
            else
                privilegesNeedLogin.add(p);
        }

        servletContext.setAttribute("privilegesNeedLogin", privilegesNeedLogin);
        servletContext.setAttribute("privilegesNeedAuth", privilegesNeedAuth);

    }

    public void contextDestroyed(ServletContextEvent sce) {

    }
}
